'''
case Type : 人为因素类
case Name ：gs_dump导出速度小于数据库数据产生速度
Create At: 2020-10-27
owner : n@ningyali
description:1、1、对表进行gs_dump操作
            2、同时开多个session对表插入大量数据
expect:1、gs_dump成功
    2、同时不影响数据插入
history：
    created： 2020/10/27  created by n@ningyali
'''
import unittest
from yat.test import Node
from yat.test import macro

from testcase.utils.CommonSH import *
from testcase.utils.Common import *
from testcase.utils.Constant import *
from testcase.utils.ComThread import *


class GsDumpAndInsert(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Human_Case017:开始执行------------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.Constant = Constant()
        self.dump_file_name = 'test_humanfactor017.tar'
        self.t_name = 't_humanfactor017'

    def test_main(self):
        self.log.info("---------------对表进行gs_dump操作----------------")
        dump_thread = ComThread(self.primary_sh.dumpFile, args=(self.dump_file_name, '-F t', None, False))
        dump_thread.setDaemon(True)
        dump_thread.start()

        time.sleep(1)

        self.log.info("---------------同时开多个session对表插入大量数据----------------")
        threads = []
        for i in range(10):
            self.log.info(f"---------------session{i}----------------")
            dml_thread = ComThread(self.com.createLargeNumTable,
                                   args=(self.primary_user_node, f'{self.t_name}_{i}', 1, 1000000,))
            threads.append(dml_thread)
            threads[i].setDaemon(True)
            threads[i].start()

        self.log.info("---------------校验gs_dump结果----------------")
        dump_thread.join(60 * 30)
        dump_result = dump_thread.get_result()
        self.log.info(dump_result)
        self.assertTrue(dump_result)

        self.log.info("------------校验多个session对表插入大量数据结果------------")
        for i in range(10):
            threads[i].join(60 * 5)
            result = threads[i].get_result()
            self.log.info(f"---------------session{i}----------------")
            self.log.info(result)
            for err_msg in self.Constant.SQL_WRONG_MSG:
                self.assertNotIn(err_msg, result)

    def tearDown(self):
        shell_cmd = f"rm -rf {self.dump_file_name}; ls {self.dump_file_name}"
        self.log.info(shell_cmd)
        msg = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(msg)

        for i in range(10):
            msg = self.com.createLargeNumTable(self.primary_user_node, f'{self.t_name}_{i}', del_sign=True)
            self.log.info(msg)
        self.log.info('------------Opengauss_Reliability_Human_Case017:执行完成------------')
